<?php

namespace App\Models;

use Database\Factories\ProductFactory;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;

/**
 * App\Models\Product
 *
 * @property int $id
 * @property string $title 产品名称
 * @property string $price 产品金额
 * @property int $stock 产品库存
 * @property int $status 产品状态
 * @property string $description 产品介绍
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property-read Price|null $currentPrice
 * @method static ProductFactory factory(...$parameters)
 * @method static Builder|Product newModelQuery()
 * @method static Builder|Product newQuery()
 * @method static Builder|Product query()
 * @method static Builder|Product whereCreatedAt($value)
 * @method static Builder|Product whereDescription($value)
 * @method static Builder|Product whereId($value)
 * @method static Builder|Product wherePrice($value)
 * @method static Builder|Product whereStatus($value)
 * @method static Builder|Product whereStock($value)
 * @method static Builder|Product whereTitle($value)
 * @method static Builder|Product whereUpdatedAt($value)
 * @mixin Eloquent
 */
class Product extends Model
{
    use HasFactory, HasDateTimeFormatter;

    /**
     *  获取产品的当前定价
     */
    public function currentPrice()
    {
        return $this->hasOne(Price::class)->ofMany([
            'published_at' => 'max',
            'id' => 'max',
        ], function ($query) {
            $query->where('published_at', '<', now());
        });
    }
}
